package com.fosung.frame.modules.sys.utils;

import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;


/**
 * http请求工具类
 * @author fire
 *
 */
public class HttpUtils {
private static transient final Logger log = LoggerFactory.getLogger(HttpUtils.class);
	
	//编码格式。发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";
	
//
//	/**
//	 * 根据传入的返回结果字符串判断调用结果是否正确
//	 * @param res
//	 * @return
//	 */
//	public static boolean checkResult(String res) {
//		boolean result = false;
//		if(StringUtils.toInteger(JsonUtil.getJsonValue(res, "code")) == 200){
//			String resultInfo = JsonUtil.getJsonValue(res, "result") + "";
//			if(StringUtils.toInteger(JsonUtil.getJsonValue(resultInfo, "retCode")) == 0){
//				result = true;
//			}
//		}
//		return result;
//	}
    
    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */

    public static String post(String url, Map<String, String> paramsMap,String clientInfo) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
            }
//            method.setHeader(HttpHeaders.CONTENT_TYPE,"text/html;charset=utf-8");
//            response.setHeader(HttpHeaders.CONTENT_TYPE,"text/html;charset=utf-8");
    	//	method.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
			method.setHeader(HttpHeaders.CONTENT_TYPE,"application/x-www-form-urlencoded");
			String encoded = new BASE64Encoder().encode(clientInfo.getBytes());//."party-build-dtdj:ido85R&Dcenter".toString("");
			String auth = "Basic "+encoded;
			method.setHeader(HttpHeaders.AUTHORIZATION,auth);
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }
    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */
    
    public static String post(String url, Object obj) {
    	if (obj == null || obj == null) {
			return null;
		}

    	CloseableHttpClient client = HttpClients.createDefault();
    	String responseText = "";
    	CloseableHttpResponse response = null;
    	try {
    		HttpPost method = new HttpPost(url);
   		method.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
    		if (obj != null) {
    			List<NameValuePair> paramList = new ArrayList<NameValuePair>();
    			PropertyDescriptor[] destDesc = PropertyUtils.getPropertyDescriptors(obj);
    			for (int i = 0; i < destDesc.length; i++) {
    				try {
    				Class origType = PropertyUtils.getPropertyType(obj, destDesc[i].getName());
    					if (null != origType && !Collection.class.isAssignableFrom(origType)) {
    							Object value = PropertyUtils.getProperty(obj, destDesc[i].getName());
//    							System.out.println("value="+value);
//    							System.out.println("name="+destDesc[i].getName());
    							NameValuePair pair = new BasicNameValuePair(destDesc[i].getName(), String.valueOf(value));
    							paramList.add(pair);
    					}
    				} catch (Exception ex) {}
    			}
//    			for (Map.Entry<String, String> param : paramsMap.entrySet()) {
//    			}
    			method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
    		}
    		response = client.execute(method);
    		HttpEntity entity = response.getEntity();
    		if (entity != null) {
    			responseText = EntityUtils.toString(entity);
    		}
    		log.info("llz====httppost==res={}", responseText);
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			response.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	return responseText;
    }
    
    public static String getURLContent(String urlStr,String urlParam,String auth) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL url = new URL(urlStr);
            // 打开和URL之间的连接
            URLConnection conn = url.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Authorization", auth);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(urlParam);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}
